package com.zcxx.cotton.pick;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.zcxx.cotton.pick.domain.PickMapElement;
import com.zcxx.cotton.pick.service.IPickMapElementService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/pick/element")
public class PickMapElementController extends BaseController {

    @Autowired
    private IPickMapElementService pickMapElementService;

    @GetMapping("/listTree")
    @ApiOperation("获取树形结构")
    public AjaxResult listTree(String name) {
        List<PickMapElement> pickMapElementList = pickMapElementService.selectPickMapElementTreeList(name);
        return AjaxResult.success(pickMapElementList);
    }

    @PostMapping("/importJSON")
    public AjaxResult batchInsertByJson(@RequestBody JSONObject object) {
        if (object.getInteger("Type") == null || !object.getInteger("Type").equals(1)){
            return AjaxResult.error("数据类型错误");
        }
        JSONArray objItems = object.getJSONArray("ObjItems");
        List<PickMapElement> elements = new ArrayList<>();
        if (objItems == null){
            return AjaxResult.error("数据为空");
        }
        buildObject(objItems, elements);

        int batchSize = 500; // 每次插入500条
        int totalItems = elements.size();
        int batches = (totalItems + batchSize - 1) / batchSize; // 计算需要多少次插入操作
        for (int i = 0; i < batches; i++) {
            List<PickMapElement> targetList = new ArrayList<>(); // 目标List
            int start = i * batchSize;
            int end = Math.min((i + 1) * batchSize, totalItems);
            targetList.addAll(elements.subList(start, end)); // 添加到目标List中
            try {
                pickMapElementService.batchInsert(targetList);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return AjaxResult.success();
    }

    private void buildObject(JSONArray objItems, List<PickMapElement> elements) {
        for (int i = 0; i < objItems.size(); i++) {
            JSONObject item = objItems.getJSONObject(i);
            JSONObject itemObj = item.getJSONObject("Object");
            JSONObject objectDetail = itemObj.getJSONObject("ObjectDetail");
            JSONArray objChildren = objectDetail.getJSONArray("ObjChildren");
            if (objChildren != null && !objChildren.isEmpty()){
                buildObject(objChildren, elements);
            }
            Integer type = itemObj.getInteger("Type");
            StringBuilder detail = new StringBuilder();
            if (type.equals(13)){
                JSONArray latlng = objectDetail.getJSONArray("Latlng");
                for (int i1 = 0; i1 < latlng.size(); i1++) {
                    Double lat = latlng.getDouble(i1);
                    detail.append(lat).append(",");
                }
            }else if (type.equals(7)){
                String lat = objectDetail.getString("Lat");
                detail.append(lat);
                String lng = objectDetail.getString("Lng");
                detail.append(",").append(lng);
            }
            try {
                //计算面积（单位：亩）
                double area = 0;
                if (type.equals(13)){
                    area = pickMapElementService.getArea(detail.toString());
                }

                PickMapElement element = new PickMapElement.Builder(item.getLong("ObjID"), item.getLong("ParentID"))
                        .name(itemObj.getString("Name"))
                        .type(type)
                        .comment(itemObj.getString("Comment"))
                        .detail(detail.toString())
                        .area(area)
                        //.category("1")
                        .build();
                elements.add(element);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    @ApiOperation("获取面积")
    @GetMapping("/getArea")
    public AjaxResult getArea(@RequestParam("coordinates") String coordinates){
        double area = pickMapElementService.getArea(coordinates);
        return AjaxResult.success(area);
    }

}
